module DB(
  input    clk,    //时钟
	input    rst,    //复位
	input    s_in_1, //输入信号——1
	input    s_in_2, //输入信号——2
	
	output    s_out_1, //输出信号——1
	output    s_out_2  //输出信号——2
    );
	
parameter	C = 15'd1;    //输入+C
parameter	D = 15'd5;    //输出-D
parameter	up_net = 15'd1000;    //溢出上限

reg    s_out_1;
reg    s_out_2;
reg  [15:0]  count_1;
reg  [15:0]  count_2;
reg  [15:0]  count_net=up_net;   
 
always @(posedge clk or negedge rst)
begin
    if(!rst)
	begin
	    count_1 <= 0;
		s_out_1 <= 0;
	end
	else if((s_in_1 == 1) && (count_1 < D))
	begin
	    count_1 <= count_1 + C;
		s_out_1 <= 0;
		if(count_1 >= count_net)    count_1 <= count_net;
	end
	else if((s_in_1 == 0) && (count_1 >= D))
	begin
	    count_1 <= count_1 - D;
		s_out_1 <= 1;
		if(count_1[15] == 1)    count_1 <= 0;		
	end
	else if((s_in_1 == 1) && (count_1 >= D))
	begin
	    count_1 <= count_1 + C - D;
		s_out_1 <= 1;
		if(count_1 >= count_net)   count_1 <= count_net;
		if(count_1[15] == 1)    count_1 <= 0;		
	end
	else
	begin
	    count_1 <= count_1;
		s_out_1 <= 0;
	end
end

always @(posedge clk or negedge rst)
begin
    if(!rst)
	begin
	    count_2 <= 0;
		s_out_2 <= 0;
	end
	else if((s_in_2 == 1) && (count_2 < D))
	begin
	    count_2 <= count_2 + C;
		s_out_2 <= 0;
		if(count_2 >= count_net)    count_2 <= count_net;
	end
	else if((s_in_2 == 0) && (count_2 >= D))
	begin
	    count_2 <= count_2 - D;
		s_out_2 <= 1;
		if(count_2[15] == 1)    count_2 <= 0;		
	end
	else if((s_in_2 == 1) && (count_2 >= D))
	begin
	    count_2 <= count_2 + C - D;
		s_out_2 <= 1;
		if(count_2 >= count_net)   count_2 <= count_net;
		if(count_2[15] == 1)    count_2 <= 0;		
	end
	else
	begin
	    count_2 <= count_2;
		s_out_2 <= 0;
	end
end

endmodule
